import Extension from '@ohos.application.ServiceExtensionAbility'
import rpc from '@ohos.rpc';
import emitter from '@ohos.events.emitter';
import Logger from '../model/Logger'

const REQUEST_VALUE = 1;

class StubTest extends rpc.RemoteObject {
    constructor(des) {
        super(des);
    }
    onRemoteRequest(code, data, reply, option) {

//        Logger.log(`onRemoteRequest: data: ${data.readString()}`);

        if (code === REQUEST_VALUE) {
            let innerEvent = JSON.parse(data.readString());
            let i = 0
            let timer = setInterval(()=> {
                i+=5;
                let flag = i === 100 ? true : false;
                var eventData = {
                    data: {
                        receivedMsg: i,
                        flag
                    }
                }
                if (i === 100) {
                    clearInterval(timer);
                    timer = null;
                    reply.writeInt(100);
                }
                emitter.emit(innerEvent, eventData)
            }, 1000)
        }
        return true;
    }

}

export default class ServiceExtAbility extends Extension {
    onCreate(want) {
        Logger.log(`onCreate, want: ${want.abilityName}`);
    }
    onRequest(want, startId) {
        Logger.log(`onRequest, want: ${want.abilityName}`);
    }
    onConnect(want) {
        Logger.log(`onConnect , want: ${want.abilityName}`);
        return new StubTest("test");
    }
    onDisconnect(want) {
        Logger.log(`onDisconnect, want: ${want.abilityName}`);
    }
    onDestroy() {
        Logger.log(`onDestroy`);
    }
}